<template>
    <div class="common-layout">
        <el-container>
            <el-header style="display: flex; align-items: center;">
                <!-- 标题 -->
                <div class="item-text" style="flex: 1;"></div>
                <div style="flex: 1;">
                    <el-row align="middle" :gutter="20" justify="start">
                        <el-col :span="8">
                            <el-input v-model="processSearchData.workOrderCode" placeholder="工单编号或编码" clearable
                                style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                                @keyup.enter.native="SearchList" />
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="primary" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                搜索
                            </el-button>
                        </el-col>
                        <!-- <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="InsertData()"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                新增
                            </el-button>
                        </el-col> -->
                    </el-row>
                </div>
            </el-header>

            <div class="mian-flex">
                <!-- 订单列表 -->
                <div class="table-container" v-loading="loading">
                    <div class="section-title">任务列表</div>

                    <!-- 工任务列表 -->
                    <div class="table-scroll-wrapper">
                        <el-table :data="detailTableData" stripe border style="width: 100%;">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50" />
                            <!-- 单据编号列，点击显示任务明细 -->
                            <el-table-column label="工序名称" prop="processName" width="100" align="center">
                                <template #default="scope">
                                    <el-link type="primary" @click="showWorkOrderDetail(scope.row.workOrderList_Id)">
                                        {{ scope.row.processName }}
                                    </el-link>
                                </template>
                            </el-table-column>
                            <el-table-column prop="processCode" label="工序编号" width="200" align="center" />
                            <el-table-column prop="submitWorkLimit" label="报工权限" width="150">
                                <template #default="scope">
                                    <span>
                                        {{ scope.row.submitWorkMatch === 1 ? '所有人' : scope.row.submitWorkLimit }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="submitWorkMatch" label="报工配比" width="150" align="center" />
                            <el-table-column prop="defectItemName" label="不良品项列表" width="400" align="center">
                                <template #default="scope">
                                    <div style="
                                    max-height: 60px;
                                    overflow-y: auto;
                                    overflow-x: hidden;
                                    word-break: break-all;
                                    padding: 4px;
                                    border: 1px solid #dcdfe6;
                                    border-radius: 4px;
                                    background: #f5f7fa;">
                                        {{ scope.row.defectItemName || ''}}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="distributionList" label="分配列表" width="150" align="center" />
                            <!-- <el-table-column prop="departmentName" label="关联单据" width="120" align="center" /> -->
                            <!-- <el-table-column label="状态" width="120" align="center">
                                <template #default="scope">
                                    <span v-if="scope.row.status === 1" type="success">未开始</span>
                                    <span v-if="scope.row.status === 2" type="warning">进行中</span>
                                    <span v-if="scope.row.status === 3" type="danger">已完成</span>
                                    <span v-if="scope.row.status === 4" type="danger">已撤回</span>
                                    <span v-if="scope.row.status === 5" type="danger">已取消</span>
                                </template>
                            </el-table-column> -->
                            <el-table-column prop="planStartDate" label="计划开始时间" width="120" align="center" />
                            <el-table-column prop="planEndDate" label="计划结束时间" width="120" align="center" />
                            <el-table-column prop="planQty" label="计划数" width="120" align="center" />
                            <el-table-column prop="goodQty" label="良品数" width="120" align="center" />
                            <el-table-column prop="noGoodQty" label="不良品数" width="200" align="center" />
                            <el-table-column prop="actualStartDate" label="实际开始时间" width="200" align="center" />
                            <el-table-column prop="actualEndDate" label="实际结束时间" width="200" align="center" />
                            <el-table-column prop="createDate" label="创建时间" width="200" align="center" />
                            <el-table-column prop="creator" label="创建人" width="200" align="center" />
                            <el-table-column prop="modifier" label="修改人" width="200" align="center" />
                            <el-table-column prop="modifyDate" label="修改时间" width="200" align="center" />
                            <el-table-column fixed="right" label="操作" min-width="100">
                                <template #default="scope">
                                    <el-row :gutter="4" style="row-gap: 12px;">
                                        <!-- <el-col :span="12">
                                            <el-button type="primary" size="small"
                                                @click="editWork()">编辑</el-button>
                                        </el-col> -->
                                        <el-col :span="12">
                                            <el-button type="danger" size="small"
                                                @click="deleteWork(scope.row.workOrderList_Id)">删除</el-button>
                                        </el-col>
                                    </el-row>
                                </template>
                            </el-table-column>

                            <!-- <el-table-column fixed="right" label="操作" min-width="230">
                                <template #default="scope">
                                    <el-row :gutter="4" style="row-gap: 12px;">
                                        <el-col :span="8">
                                            <el-button type="primary" size="small"
                                                @click="changeWork(scope.row.workOrder_Id, 2)">开始</el-button>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-button type="info" size="small"
                                                @click="changeWork(scope.row.workOrder_Id, 5)">取消</el-button>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-button type="success" size="small"
                                                @click="changeWork(scope.row.workOrder_Id, 3)">结束</el-button>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-button type="warning" size="small"
                                                @click="changeWork(scope.row.workOrder_Id, 4)">撤回</el-button>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-button type="danger" size="small"
                                                @click="changeWork(scope.row.workOrder_Id, 6)">删除</el-button>
                                        </el-col>

                                    </el-row>
                                </template>
                            </el-table-column> -->
                        </el-table>
                    </div>

                    <div class="demo-pagination-block"
                        style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
                    </div>

                </div>

                <!-- 任务明细弹窗 -->
                <el-dialog v-model="detailDialogVisible" class="fixed-size-dialog" width="80%"
                    :before-close="handleClose">
                    <!-- 自定义标题 -->
                    <template #title>
                        <div style="display: flex; flex-direction: column;">
                            <span style="font-size: 20px; font-weight: bold;">任务明细(编辑)</span>
                        </div>
                    </template>

                    <div class="dialog-body">
                        <div class="form-section">
                            <!-- 表单 -->
                            <el-form :model="orderInfodetail" label-width="120px" class="order-detail-form"
                                label-position="right">
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-form-item label="工单编号:">
                                            <el-input v-model="orderInfodetail.workOrderCode" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工单编号:">
                                            <el-input v-model="orderInfodetail.workOrderCode" disabled />
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="8">
                                        <el-form-item label="工序名称:">
                                            <el-input v-model="orderInfodetail.processName" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="工序编号:">
                                            <el-input v-model="orderInfodetail.processCode" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="报工权限:">
                                            <el-input v-model="orderInfodetail.submitWorkLimit" disabled />
                                        </el-form-item>
                                    </el-col> -->

                                    <el-col :span="8">
                                        <el-form-item label="报工权限:">
                                            <!-- <span>{{orderInfodetail.employeeIds}}</span> -->
                                            <!-- <span>{{employeeOptions}}</span> -->
                                            <!-- multiple 实现多选 -->
                                            <el-select v-model="orderInfodetail.submitWorkLimit" multiple clearable
                                                collapse-tags-tooltip placeholder="请选择员工" style="width: 100%">
                                                <el-option v-for="emp in employeeOptions" :key="emp.id"
                                                    :label="emp.employeesName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="报工权限比:">
                                            <el-input-number v-model="orderInfodetail.submitWorkMatch" :min="1"
                                                controls-position="right" size="large" width="100%" />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="计划数:">
                                            <el-input v-model="orderInfodetail.planQty" disabled />
                                        </el-form-item>
                                    </el-col> -->

                                    <el-col :span="8">
                                        <el-form-item label="计划数">
                                            <el-input-number v-model="orderInfodetail.planQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="良品数:">
                                            <el-input v-model="orderInfodetail.goodQty" disabled />
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="8">
                                        <el-form-item label="良品数">
                                            <el-input-number v-model="orderInfodetail.planQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="不良品数:">
                                            <el-input v-model="orderInfodetail.noGoodQty" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="分配列表:">
                                            <el-input v-model="orderInfodetail.distributionList" disabled />
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="8">
                                        <el-form-item label="分配列表:">
                                            <el-select v-model="orderInfodetail.distributionList" multiple clearable
                                                collapse-tags-tooltip placeholder="请选择员工" style="width: 100%">
                                                <el-option v-for="emp in employeeOptions" :key="emp.id"
                                                    :label="emp.employeesName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="实际开始时间:">
                                            <el-input v-model="orderInfodetail.actualStartDate" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="实际结束时间:">
                                            <el-input v-model="orderInfodetail.actualEndDate" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="计划开始时间:">
                                            <el-date-picker v-model="orderInfodetail.planStartDate" type="datetime"
                                                placeholder=orderInfodetail.planStartDate style="width:100%;" />
                                            <!-- <el-input v-model="orderInfodetail.planStartDate"  /> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="计划结束时间:">
                                            <el-date-picker v-model="orderInfodetail.planEndDate" type="datetime"
                                                placeholder=orderInfodetail.planEndDate style="width:100%;" />
                                            <!-- <el-input v-model="orderInfodetail.planEndDate"  /> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="不良品列表:">
                                            <!-- <span>{{ orderInfodetail.defectItemIds }}</span> -->
                                            <!-- <el-input v-model="orderInfodetail.defectItemName" /> -->
                                            <el-select v-model="orderInfodetail.defectItemIds" multiple clearable
                                                collapse-tags-tooltip :placeholder="请选择不良品" style="width: 100%">
                                                <el-option v-for="emp in defectItemOptions" :key="emp.defectItem_Id"
                                                    :label="emp.defectItemCode + '|' + emp.defectItemName"
                                                    :value="emp.defectItem_Id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 分割线 -->
                    <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                    <!-- 下部分：订单明细表格 -->
                    <!-- <div class="table-section">
                        <el-table :data="orderInfodetail" style="width: 100%;" stripe border>
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="processName" label="工序名称" width="230">
                                <template #default="scope">
                                    <span v-if="scope.row.processName">
                                        {{ scope.row.processName }}
                                    </span>
                                    <span v-else style="color: red; font-weight: bold;">
                                        null
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="processCode" label="工序编号" width="200" />
                            <el-table-column prop="defectItemName" label="不良品项列表" width="300" />
                            <el-table-column prop="submitWorkLimit" label="报工权限" width="200">
                                <template #default="scope">
                                    <span>
                                        {{ scope.row.submitWorkMatch === 1 ? '所有人' : scope.row.submitWorkLimit }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="submitWorkMatch" label="报工数配比" width="200" />
                            <el-table-column prop="planStartDate" label="计划开始时间" width="250" />
                            <el-table-column prop="planEndDate" label="计划结束时间" width="250" />
                            <el-table-column prop="planQty" label="计划数" width="50" />
                        </el-table>
                    </div> -->

                    <template #footer>
                        <el-button @click="saveEdit()">确认</el-button>
                        <el-button @click="detailDialogVisible = false">关闭</el-button>
                    </template>
                </el-dialog>

                <!-- 新增工单弹窗 -->
                <el-dialog v-model="insertDialogVisiable" width="80%" :before-close="handleInsertClose">
                    <!-- 标题栏 -->
                    <template #title>
                        <div sttle="dispaly: flex; flex-direction: column;">
                            <span style="font-size: 20px; font-weight: bold;">新增工单</span>
                            <div style="margin-top:20px; border-bottom: 1px solid #dcdfe6;"></div>
                        </div>
                    </template>


                    <!-- 上半部分表单 -->
                    <div class="dialog-body">
                        <div class="form-section">
                            <el-form :model="insertForm" label-width="120px" class="order-detail-form"
                                label-position="right">
                                <el-row :gutter="20">

                                    <el-col :span="12">
                                        <el-form-item label="工单编号">
                                            <el-input v-model="insertForm.workOrderCode" placeholder="请输入工单编号" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="存货">
                                            <el-input v-model="insertForm.inventoryName" readonly
                                                @click="openInventoryDialog()" placeholder="选择存货" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="计划开始时间">
                                            <el-date-picker v-model="insertForm.planStartDate" type="datetime"
                                                placeholder="选择计划开始时间" style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="计划结束时间">
                                            <el-date-picker v-model="insertForm.planEndDate" type="datetime"
                                                placeholder="选择计划结束时间" style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="计划数">
                                            <el-input-number v-model="insertForm.planQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="报工时长">
                                            <el-date-picker v-model="insertForm.reportTime" type="datetime"
                                                placeholder="选择报工时长" style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24">
                                        <el-form-item label="备注">
                                            <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>

                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 分割线 -->
                    <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                    <!-- 下半部分：可新增工序的表格 -->
                    <div class="table-section">
                        <el-button type="primary" @click="addRow" style="margin-bottom: 10px;">新增一行</el-button>
                        <el-table :data="insertTableData" style="width: 100%;" border stripe>

                            <el-table-column type="index" label="序号" width="50" />

                            <el-table-column prop="process_Id" label="工序" width="150">
                                <!-- @click="openProcessDialog(scope.row), loadingProcessData()" -->
                                <template #default="scope">
                                    <el-input v-model="scope.row.processName" readonly
                                        @click="openProcessDialog(scope.row)" placeholder="选择工序" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="submitWorkMatch" label="报工数配比" width="150">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.submitWorkMatch" :min="0" :max="1"
                                        :step="0.1" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="defectItemName" label="不良品项" width="300">
                                <template #default="scope">
                                    <el-input v-model="scope.row.defectItemName" placeholder="填写不良品项" disabled />
                                </template>
                            </el-table-column>

                            <el-table-column prop="planStartDate" label="计划开始时间" width="250">
                                <template #default="scope">
                                    <el-date-picker v-model="scope.row.planStartDate" type="datetime"
                                        placeholder="选择开始时间" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="planEndDate" label="计划结束时间" width="250">
                                <template #default="scope">
                                    <el-date-picker v-model="scope.row.planEndDate" type="datetime"
                                        placeholder="选择结束时间" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="planQty" label="计划数" width="180">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.planQty" :min="1" />
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button type="danger" @click="removeRow(scope.$index)"
                                        size="small">删除</el-button>
                                </template>
                            </el-table-column>

                        </el-table>
                    </div>

                    <template #footer>
                        <el-button @click="handleInsertClose()">取消</el-button>
                        <el-button type="primary" @click="saveInsert()">保存</el-button>
                    </template>
                </el-dialog>

                <!-- 存货选择弹窗 -->
                <el-dialog v-model="inventoryDialogVisible" width="1200px" :close-on-click-modal="false"
                    :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                    <template #title>
                        <span style="font-weight: bold;">选择存货</span>
                    </template>

                    <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                        <el-input v-model="inventorySearchData.Code" placeholder="存货编号或编码" clearable
                            style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                            @keyup.enter.native="handleSearch" />

                        <el-button type="primary" @click="handleSearch"
                            style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                            搜索
                        </el-button>
                    </div>

                    <!-- 表格滚动容器 -->
                    <div class="table-scroll-wrapper">
                        <el-table :data="inventoryOptions" stripe border style="width: 100%;"
                            @selection-change="handleSelectionChange">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50"
                                :selectable="(row, index) => !!row.processLineName" />
                            <el-table-column prop="inventoryCode" label="产品编号" width="250" />
                            <el-table-column prop="inventoryName" label="产品名称" width="220" />
                            <el-table-column prop="unitName" label="单位" width="120" />
                            <el-table-column prop="specificationModel" label="产品规格" width="290" />
                            <el-table-column prop="processLineName" label="工艺路线" width="180" />
                        </el-table>
                    </div>

                    <!-- 分页部分 -->
                    <div class="demo-pagination-block"
                        style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChangeInventory"
                            @size-change="handleSizeChangeInventory" />
                    </div>

                    <!-- 底部按钮 -->
                    <template #footer>
                        <div style="text-align: right;">
                            <el-button @click="inventoryDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="confirmInventory">确定</el-button>
                        </div>
                    </template>
                </el-dialog>

                <!-- 工序选择弹窗 -->
                <el-dialog v-model="processDialogVisible" width="1200px" :close-on-click-modal="false"
                    :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                    <template #title>
                        <span style="font-weight: bold;">选择工序</span>
                    </template>

                    <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                        <el-input v-model="processSearchData.workOrderCode" placeholder="工序编号或编码" clearable
                            style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                            @keyup.enter.native="handleProcessSearch" />

                        <el-button type="primary" @click="handleProcessSearch"
                            style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                            搜索
                        </el-button>
                    </div>

                    <!-- 表格滚动容器 -->
                    <div class="table-scroll-wrapper">
                        <el-table :data="processOptions" stripe border style="width: 100%;"
                            @selection-change="handleProcessSelectionChange">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50" />
                            <el-table-column prop="processCode" label="工序编号" width="200" />
                            <el-table-column prop="processName" label="工序名称" width="200" />
                            <el-table-column prop="submitWorkLimit" label="报工权限" width="150" />
                            <el-table-column prop="submitWorkMatch" label="报工权限比" width="200" />
                            <el-table-column prop="defectItemName" label="不良品项列表" width="300" />
                            <!-- <el-table-column prop="defectItemName" label="不良品项列表" width="300">
                                <template #default="scope">
                                    {{ mergeDefectItems(scope.row.processCode) }}
                                </template>
                            </el-table-column> -->

                        </el-table>
                    </div>

                    <!-- 分页部分 -->
                    <div class="demo-pagination-block"
                        style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChangeProcess"
                            @size-change="handleSizeChangeProcess" />
                    </div>

                    <!-- 底部按钮 -->
                    <template #footer>
                        <div style="text-align: right;">
                            <el-button @click="handleInsertClose()">取消</el-button>
                            <el-button type="primary" @click="confirmProcess">确定</el-button>
                        </div>
                    </template>
                </el-dialog>

            </div>
        </el-container>
    </div>
</template>

<script setup>
import { ref, watch, reactive, computed, watchEffect, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import {
    WorkOrderSearchList,
    WorkOrderSearchListDetail,
    getInventory,
    getProcess,
    getProcessCode,
    addProcess,
    changeWorkStatus,
    getWorkorderList,
    getEmployees,
    getDefectItem,
    updateWorkOrderList,
    deleteWorkOrderList
} from '../../extension/V2/WorkOrderList'

const cities = [
    { value: 'Beijing', label: 'Beijing' },
    { value: 'Shanghai', label: 'Shanghai' },
    { value: 'Nanjing', label: 'Nanjing' },
    { value: 'Chengdu', label: 'Chengdu' },
    { value: 'Shenzhen', label: 'Shenzhen' },
    { value: 'Guangzhou', label: 'Guangzhou' },
]

const exmaple = ref([])

// 搜索条件模型
const searchModel = ref({ WorkOrderCode: '' })

// 表格数据与分页数据
const detailTableData = ref([]) // 订单展示明细模型
const detailDialogVisible = ref(false)

let loading = ref(false)

const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

const orderInfodetail = ref([{
    workOrderCode: '',
    SubmitWorkLimit: '',
    productStandard: '',
    inventoryCode: '',
    unitName: '',
    planStartDate: '',
    planEndDate: '',
    planQty: '',
    status: '',
    remark: '',
    WorkOrderList_Id: '',
    SubmitWorkMatch: '',
    DefectItemName: '',
    employeeIds: '',
    defectItemIds: ''
}])


const statusText = (status) => {
    switch (status) {
        case 1: return '未开始';
        case 2: return '进行中';
        case 3: return '已完成';
        case 4: return '已撤回';
        case 5: return '已取消';
        default: return '';
    }
}

const statusColor = (status) => {
    switch (status) {
        case 1: return 'green';
        case 2: return '#e6a23c'; // 警告色
        case 3: return 'red';
        case 4: return 'gray';
        case 5: return 'gray';
        default: return 'black';
    }
}

// 获取当前分页+搜索参数
const getParams = () => ({
    WorkOrderCode: searchModel.value.WorkOrderCode,
    page: currentPage.value,
    rows: pageSize.value,
    sort: 'desc',
    order: 'CreateDate'
})

// 分页页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page
    Search()
}

// 分页每页条数变化
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    Search()
}

// 查询方法 (分页变化,自动渲染)
const Search = async () => {
    loading = true
    const params = getProcessParams()
    console.log("已执行params：", params)

    try {
        const result = await getWorkorderList(params)
        console.log("已执行result：", result)
        console.log("已执行result.status：", result.status)
        if (result.status === 0) {
            detailTableData.value = result.rows || []
            totalCount.value = result.total || 0
            loading = false
        } else {
            detailTableData.value = []
            totalCount.value = 0
            ElMessage.error(result.msg || '查询失败')
        }
    } catch (error) {
        console.error('查询异常:', error)
    }
}

// 搜索按钮
const SearchList = async () => {
    const params = getProcessParams()
    console.log("SearchList已执行params：", params)
    console.log("WorkOrderCode:" )
    const result = await getWorkorderList(params)
    if (result.status === 0) {
        detailTableData.value = result.rows
        totalCount.value = result.total
    } else {
        detailTableData.value = []
        totalCount.value = 0
        ElMessage.error(result.msg || '查询失败')
    }
}


// 任务明细部分
// const showWorkOrderDetailData = async (workOrder_Id) => {
//     const result = await WorkOrderSearchListDetail(workOrder_Id)
//     orderInfodetail.value = result.rows || []
//     console.log("orderInfodetail:", orderInfodetail.value)
// }

// 任务明细部分
const showWorkOrderDetail = (workOrderList_Id) => {
    detailDialogVisible.value = true

    // 在 detailTableData 中找到对应行的数据
    const rowData = detailTableData.value.find(item => item.workOrderList_Id === workOrderList_Id)

    if (rowData) {
        orderInfodetail.value = rowData   // 直接赋值给明细数据
        console.log("拿到数据orderInfodetail:", orderInfodetail.value)
    } else {
        orderInfodetail.value = {}        // 没找到时清空
        ElMessage.warning('未找到对应的工序明细')
    }
}

// 弹窗滚动控制
watch(() => detailDialogVisible.value, (val) => {
    document.body.style.overflow = val ? 'hidden' : ''
})


// 新增工单方法 ----

const insertDialogVisiable = ref(false) //定义新增弹窗

// 定义新增工单模型
const insertForm = ref({
    workOrderCode: '',
    inventoryName: '',
    inventory_Id: '',
    planStartDate: '',
    planEndDate: '',
    planQty: 0,
    reportTime: '',
    remark: '',
    productionWorkOrderDetails: []
})

//定义选择存货弹窗
const inventoryDialogVisible = ref(false)

// 关闭时清空数据
// const handleInsertClose = () => {
//     Object.assign(insertForm.value, {
//         workOrderCode: '',
//         inventoryName: '',
//         inventory_Id: '',
//         planStartDate: '',
//         planEndDate: '',
//         planQty: 0,
//         reportTime: '',
//         remark: '',
//     })
//     // insertTableData.value = []
//     insertDialogVisiable.value = false
// }

// 定义 点击打开新增弹窗
const InsertData = () => {
    insertDialogVisiable.value = true
    GetProcessCode()
}

// 定义用户输入的搜索内容
const inventorySearchData = reactive({
    Code: ''
})

// 定义 存货分页
const inventoryCurrentPage = ref(1)
const inventoryPageSize = ref(15)
const inventoryTotal = ref(0)

// 当前正在编辑的订单行
const currentRow = ref(null)

// // 定义用户输入的搜索内容
// const inventorySearchData = reactive({
//     Code: ''
// })

// 获取存货搜索参数
const getProductParams = () => {
    const wheresArr = []
    if (inventorySearchData.Code) {
        wheresArr.push({
            name: 'inventoryCode',       // 搜索字段名
            value: String(inventorySearchData.Code || ''),
            displayType: 'like'          // 模糊匹配
        })
    }

    return {
        page: inventoryCurrentPage.value,
        rows: inventoryPageSize.value,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify(wheresArr)  // 转为 JSON 字符串
    }
}

// 打开弹窗并加载存货数据
const openInventoryDialog = async (row) => {
    currentRow.value = row
    inventoryDialogVisible.value = true
    inventoryCurrentPage.value = 1   // 打开时回到第一页
}

// 分页页码变化
const handleCurrentChangeInventory = (page) => {
    inventoryCurrentPage.value = page
    loadingInventoryData()
    // Search()
}

// 分页每页条数变化
const handleSizeChangeInventory = (rows) => {
    console.log("页大小变化:", rows)
    inventoryPageSize.value = rows
    inventoryCurrentPage.value = 1
    loadingInventoryData()
    console.log("页大小变化pageSize.value:", pageSize.value)
}

// 定义存货响应数据
const inventoryOptions = ref([])
//加载存货数据
const loadingInventoryData = async () => {
    try {
        const params = getProductParams()
        console.log("数据加载getInventory()")
        const res = await getInventory(params)
        console.log("数据加载成功getInventory（）", res)
        inventoryOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

//  选择存货弹窗搜索功能
const handleSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingInventoryData()
}

// 当前选中的存货（单选）
const selectedInventory = ref([])
// 表格勾选事件（这里用单选，所以取第一条）
const handleSelectionChange = (val) => {
    selectedInventory.value = val
}

// 确认选择
const confirmInventory = () => {
    if (!selectedInventory.value || selectedInventory.value.length === 0) {
        ElMessage.warning("请选择至少一条存货")
        return
    }

    // 取第一个选中的存货
    const first = selectedInventory.value[0]
    console.log("确认选择:", first)

    // 注意：后端查出来是 id，这里转成新增接口需要的 inventory_Id
    insertForm.value.inventoryName = first.inventoryName
    insertForm.value.inventory_Id = first.id   // 用后端返回的 id

    // 关闭弹窗并清空已选
    inventoryDialogVisible.value = false
    selectedInventory.value = []
}

// 新增下半部分表格数据
const insertTableData = ref([])

// 添加新一行工序
const addRow = () => {
    insertTableData.value.push({
        process_Id: null,           // 工序
        submitWorkMatch: 0,         // 报工数配比，默认0
        defectItemName: '',             // 不良品项
        planStartDate: '',          // 计划开始时间
        planEndDate: '',            // 计划结束时间
        planQty: '',                 // 计划数，默认1
        inventoryName: '',          // 产品名称--存货
        inventoryId: '',          // 存货ID
        inventoryCode: '',          // 产品编号--存货
        specificationModel: '',     // 产品规格--存货
        FinishedProduct: 0,         // 完成数，默认0
        CreateDate: '',             // 创建时间
        CreateID: '',               // 创建人id
        Creator: '',                // 创建人
        Modifier: '',               // 修改人
        ModifyDate: ''              // 修改时间
    })
}
// 字段监听，实现计划开始，结束时间，计划数上下部分数据同步
watch(
    () => insertForm.value.planStartDate,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planStartDate = newVal
        })
    }
)

watch(
    () => insertForm.value.planEndDate,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planEndDate = newVal
        })
    }
)

watch(
    () => insertForm.value.planQty,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planQty = newVal
        })
    }
)

// 定义新增工序模型
const processForm = ref({
    workOrderCode: '',
    inventoryName: '',
    inventory_Id: null,
    planStartDate: '',
    planEndDate: '',
    planQty: 0,
    reportTime: '',
    remark: '',
    productionWorkOrderDetails: []
})

// 当前正在编辑的工序行
const currentProcessRow = ref(null)
const currentProcessPage = ref(1)

//定义选择工序弹窗
const processDialogVisible = ref(false)
// 打开弹窗并加载工序数据数据
const openProcessDialog = async (row) => {
    currentProcessRow.value = row
    processDialogVisible.value = true
    currentProcessPage.value = 1   // 打开时回到第一页
}

// 定义用户输入的搜索内容 ---任务
const processSearchData = reactive({
    workOrderCode: ''
})

// 选择工序搜索功能
const handleProcessSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingProcessData()
}

// // 定义用户输入的搜索内容 --工序
// const processSearchData = reactive({
//     Code: ''
// })

// 获取工序搜索参数
// 获取工序搜索参数
const getProcessParams = () => {
    return {
        // 对应 QueryBaseModel 的分页字段
        page: currentPage.value,   // 当前页码
        rows: pageSize.value,      // 每页大小
        sort: 'CreateDate',               // 排序字段
        order: 'asc',                    // 排序方式

        // 对应 SearchWorkOrderModel 的字段
        WorkOrderCode: processSearchData.workOrderCode || ''
    }
}
// 定义存货响应数据
const processOptions = ref([])
// 加载工序数据
const loadingProcessData = async () => {
    try {
        const params = getProcessParams()
        console.log("数据加载params", params)
        const res = await getWorkorderList(params)
        console.log("数据加载成功getWorkorderList（）", res)
        processOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载任务数据异常:', err)
    }
}

// 当前选中的工序（单选）
const selectedProcess = ref([])
// 表格勾选事件（这里用单选，所以取第一条）
const handleProcessSelectionChange = (val) => {
    selectedProcess.value = val
}

// 定义 工序分页
const processCurrentPage = ref(1)
const processPageSize = ref(15)
const prcessTotal = ref(0)

// 分页页码变化
const handleCurrentChangeProcess = (page) => {
    processCurrentPage.value = page
    loadingProcessData()
    // Search()
}

// 分页每页条数变化
const handleSizeChangeProcess = (rows) => {
    console.log("页大小变化:", rows)
    processPageSize.value = rows
    processCurrentPage.value = 1
    loadingProcessData()
    console.log("页大小变化pageSize.value:", processPageSize.value)
}

// 确认选择 --- 工序回显
// const confirmProcess = () => {
//   if (!currentProcessRow.value || !selectedProcess.value.length) return

//   const selected = selectedProcess.value[0]

//   // 按弹窗列字段回显
//   currentProcessRow.value.processCode = selected.processCode
//   currentProcessRow.value.processName = selected.processName
//   currentProcessRow.value.submitWorkLimit = selected.submitWorkLimit
//   currentProcessRow.value.submitWorkMatch = selected.submitWorkMatch
//   currentProcessRow.value.defectItem = selected.defectItem

//   // 关闭弹窗
//   processDialogVisible.value = false
// }

// // 用 Map 先把同工序的 defectItemName 合并
// const mergeDefectItems = (processCode) => {
//   // 找到同工序的所有行
//   const rows = processOptions.value.filter(item => item.processCode === processCode)

//   // 提取 defectItemName，去重
//   const defectSet = new Set()
//   rows.forEach(r => {
//     if (r.defectItemName) {
//       defectSet.add(r.defectItemName)
//     }
//   })

//   // 返回合并后的字符串
//   return Array.from(defectSet).join(' | ')
// }

// // 去重后的数组，供表格渲染
// const mergedProcessOptions = computed(() => {
//   const map = new Map()
//   processOptions.value.forEach(row => {
//     if (!map.has(row.processCode)) {
//       map.set(row.processCode, row)
//     }
//   })
//   return Array.from(map.values())
// })

// 删除行
const removeRow = (index) => {
    insertTableData.value.splice(index, 1)
}

// 确认选择 --- 工序回显
const confirmProcess = () => {
    if (!currentProcessRow.value || selectedProcess.value.length === 0) {
        ElMessage.warning("请选择至少一条工序")
        return
    }

    const first = selectedProcess.value[0]

    // 回显到当前行
    Object.assign(currentProcessRow.value, {
        processName: first.processName,
        processCode: first.processCode,           // 工序编号
        process_Id: first.process_Id,
        submitWorkLimit: first.submitWorkLimit,   // 报工权限
        submitWorkMatch: first.submitWorkMatch,
        defectItemName: first.defectItemName,
        planStartDate: insertForm.value.planStartDate,
        planEndDate: insertForm.value.planEndDate,
        planQty: insertForm.value.planQty
    })

    // 剩余选中工序新增行
    for (let i = 1; i < selectedProcess.value.length; i++) {
        const item = selectedProcess.value[i]
        insertTableData.value.push({
            processName: item.processName,
            processCode: item.processCode,
            process_Id: item.process_Id,
            inventoryId: item.inventoryId,
            submitWorkLimit: item.submitWorkLimit,
            submitWorkMatch: item.submitWorkMatch,
            defectItemName: item.defectItemName,
            planStartDate: item.planStartDate,
            planEndDate: item.planEndDate,
            planQty: item.planQty
        })
    }

    processDialogVisible.value = false
    selectedProcess.value = [] // 清空已选
}

// 自动获取生产计划单据编号
const GetProcessCode = async () => {
    try {
        const res = await getProcessCode()
        console.log("获取工单编号成功:", res)
        if (res && res.data) {
            insertForm.value.workOrderCode = res.data
            console.log("获取工单编号成功res.data:", res.data)
            console.log("获取工单编号成功insertForm.value.workOrderCode:", insertForm.value.workOrderCode)
        }
    } catch (err) {
        console.error('获取工单编号失败:', err)
        ElMessage.error('获取工单编号失败')
    }
}

const employeeOptions = ref([])
// 获取员工数据
const loadEmployees = async () => {
    try {
        console.log("111员工数据加载")
        const result = await getEmployees()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            employeeOptions.value = result.rows || []
            console.log("employeeOptions:", employeeOptions.value)
        } else {
            ElMessage.error(result.msg || '获取员工数据失败')
        }
    } catch (err) {
        console.error('获取员工数据异常:', err)
    }
}

const defectItemOptions = ref([])

// 获取不良品数据
const loadDefectItem = async () => {
    try {
        console.log("111员工数据加载")
        const result = await getDefectItem()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            defectItemOptions.value = result.rows || []
            console.log("defectItemOptions:", defectItemOptions.value)
        } else {
            ElMessage.error(result.msg || '获取不良品数据失败')
        }
    } catch (err) {
        console.error('获取不良品数据异常:', err)
    }
}

//添加工单
// const saveInsert = async () => {
//     console.log("进入添加工单insertForm.value", insertForm.value)
//     try {
//         const res = await addProcessCode(insertForm.value)
//         console.log("添加工单成功:", res)
//         if (res && res.data) {
//             ElMessage.success('添加工单成功')
//             insertForm.value = {}
//             insertTableData.value = []
//             Search()
//         }
//     } catch (err) {
//         console.error('添加工单失败:', err)
//         ElMessage.error('添加工单失败')
//     }
// }

// 关闭时清空数据
const handleInsertClose = () => {

    insertDialogVisiable.value = false

    Object.assign(insertForm.value, {
        workOrderCode: '',
        planStartDate: '',
        planEndDate: '',
        planQty: '',
        reportTime: '',
        remark: '',
        inventory_Id: '',
        inventoryName: ''

    })
    insertTableData.value = []
}

// 添加工单
const saveInsert = async () => {

    console.log("保存前的 insertForm:", insertForm.value)


    try {
        // 构造请求参数
        const payload = {
            workOrderCode: insertForm.value.workOrderCode || "",     // 单据编号
            planStartDate: insertForm.value.planStartDate || "",     // 计划开始时间
            planEndDate: insertForm.value.planEndDate || "",     // 计划结束时间
            planQty: insertForm.value.planQty || "",     // 计划数
            reportTime: insertForm.value.reportTime || "",     // 报工时长
            remark: insertForm.value.remark || "",   // 备注
            inventory_Id: insertForm.value.inventory_Id || "",     // 存货ID
            productionWorkOrderDetails: insertTableData.value.map(row => {
                return {
                    process_Id: row.process_Id,  // 存货ID
                    submitWorkMatch: row.submitWorkMatch,          // 报工数配比
                    defectItem: row.defectItemName,                 // 不良项
                    planStartDate: row.planStartDate,               // 计划开始时间
                    planEndDate: row.planEndDate,                   // 计划结束时间
                    planQty: row.planQty,                             // 计划数
                }
            })
        }

        // 校验工作结束时间
        if (!payload.inventory_Id) {
            ElMessage.error('请填写存货')
            return
        }

        // 校验工作开始时间
        if (!payload.planStartDate) {
            ElMessage.error('请填写计划开始时间')
            return
        }

        // 校验工作结束时间
        if (!payload.planEndDate) {
            ElMessage.error('请填写计划结束时间')
            return
        }

        if (payload.productionWorkOrderDetails.length === 0) {
            ElMessage.error('至少新增一条工单')
            return
        }

        if (payload.productionWorkOrderDetails.some(row => !row.planQty) || payload.productionWorkOrderDetails.some(row => !row.process_Id)) {
            ElMessage.error('请填写工序和计划数')
            return
        }

        if (payload.productionWorkOrderDetails.some(row => !row.planStartDate) || payload.productionWorkOrderDetails.some(row => !row.planEndDate)) {
            ElMessage.error('请填写计划开始时间和计划结束时间')
            return
        }


        console.log('请求参数 payload:', payload)

        //调用新增接口
        const result = await addProcess(payload)
        console.log("接口返回 result:", result)

        if (result && result.ok === true) {
            ElMessage.success(
                (result && result.err && result.err.msg) || '新增工单成功'
            )
            Search()
            handleInsertClose()
        } else {
            ElMessage.error(
                (result && result.err && result.err.msg) || '新增工单失败'
            )
        }
    } catch (err) {
        console.error('保存异常:', err)
        ElMessage.error('保存异常')
    }
}





// 初始化
Search()
loadingInventoryData()
loadEmployees()
loadDefectItem()
// loadingProcessData()

//修改工单状态
const changeWork = async (workOrder_Id, status) => {
    try {
        const params = {
            WorkOrder_Id: workOrder_Id,
            Status: status
        }
        const res = await changeWorkStatus(params)

        if (res && res.data) {
            ElMessage.success('工单状态更新成功')
            Search()
        } else {
            ElMessage.error('工单状态更新失败')
        }
    } catch (error) {
        console.error('工单状态更新异常:', error)
        ElMessage.error('请求出错')
    }
}

// 编辑任务
const editWork = async () => {
    detailDialogVisible.value = true
}

const saveEdit = async () => {
    const defectItemName = toRaw(orderInfodetail.value.defectItemIds).join(',');
    const payload = {
        ...orderInfodetail.value,
        // 多选字段转换成逗号分隔字符串
        submitWorkLimit: orderInfodetail.value.submitWorkLimit.join(','),
        distributionListIds: orderInfodetail.value.distributionList.join(','),
        defectItemName: orderInfodetail.value.defectItemIds.join(','),

    };

    // 校验工作结束时间
    if (!payload.submitWorkLimit) {
        ElMessage.error('请填写报工权限')
        return
    }

    // 校验工作开始时间
    if (!payload.distributionListIds) {
        ElMessage.error('请填写报工配比')
        return
    }

    // 校验工作结束时间
    if (!payload.defectItemName) {
        ElMessage.error('请填写不良品项')
        return
    }

    console.log("编辑前的 payload:", payload)
    console.log("编辑前的 defectItemName:", defectItemName)
    console.log("编辑前的 orderInfodetail.value.defectItemIds:", toRaw(orderInfodetail.value.defectItemIds))
    const res = await updateWorkOrderList(payload);
    if (res.ok === true) {
        ElMessage.success('编辑成功');
        detailDialogVisible.value = false;
        // fetchDetailTableData();
    } else {
        ElMessage.error('编辑失败：' + res.message);
    }
}
// 删除任务
const deleteWork = async (id) => {

    console.log("删除的id:", id)
    const params = {
        id: id
    }

    const res = await deleteWorkOrderList(id)
    if (res.item1 === true) {
        ElMessage.success('删除成功');
        Search();
    } else {
        ElMessage.error('删除失败：' + (res.item2.msg || "未知错误"));
    }
    //TODO
}
</script>

<style scoped>
.el-table .defect-cell .cell-box {
    max-width: 140px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
    padding: 2px 4px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: #f5f7fa;
}

.el-table .defect-cell .cell-box.expanded {
    white-space: normal;
    /* 允许换行 */
    max-width: 400px;
    /* 点击后放大 */
    background: #fff;
    position: absolute;
    /* 保证不会被挤压 */
    z-index: 10;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.table-container {
    background-color: #ffffff;
    border: 1px solid #ebeef5;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 表格滚动容器 */
.table-scroll-wrapper {
    height: 500px;
    /* 固定表格高度 */
    overflow: auto;
    /* 表体滚动 */
}

/* 表头固定 */
.el-table th {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
}

/* 表格文字居中 */
::v-deep(.el-table th, .el-table td) {
    text-align: center;
}

/* 其他样式保持不变 */
.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    padding-bottom: 6px;
    border-bottom: 2px solid #333;
    display: inline-block;
}
</style>
